package com.example.Controller;

import com.example.Service.SmsResponse;
import com.example.Service.SmsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping
@Slf4j
public class SmsController {

    @Resource
    private SmsService smsService;

    @Resource
    private RedisTemplate<String, String> redisTemplate;


    @PostMapping("/send-sms-code")
    public SmsResponse sendCode(@RequestParam String phone) {
        // 生成随机验证码
        String code = String.valueOf((int) ((Math.random() * 9 + 1) * 100000));

        // 使用UUID生成验证码标识
        String verificationId = UUID.randomUUID().toString();

        // 将验证码和标识存储到Redis中，并设置过期时间
        redisTemplate.opsForValue().set("SMS_" + verificationId, code, 60, TimeUnit.MINUTES);

        // 发送验证码短信并将verificationId作为标识返回
        boolean success = smsService.sendVerificationCode(phone, code);

        if (success) {
            // 返回包含 phoneNumber 和 verificationId 的响应
            return new SmsResponse(phone, verificationId,code);
        } else {
            // 如果发送失败，可以返回 null 或者其他错误信息
            return null;
        }
    }
}
